<template>
  <div class="order-container">
    <!-- 状态导航 -->
    <div class="status-nav">
      <el-radio-group
          v-model="activeStatus"
          @change="handleStatusChange"
          size="large"
          class="status-tabs"
      >
        <el-radio-button
            v-for="tab in orderTabs"
            :key="tab.status"
            :label="tab.status"
            border
        >
          <el-icon :size="18" class="tab-icon">
            <component :is="tab.icon" />
          </el-icon>
          {{ tab.label }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 加载状态 -->
    <el-skeleton :rows="5" animated v-if="loading" />

    <!-- 空状态 -->
    <el-empty
        v-else-if="orders.length === 0"
        :description="`暂无${currentTabLabel}订单`"
        class="empty-box"
    >
<!--      <img src="@/assets/empty-order.png" class="empty-image" />-->
    </el-empty>

    <!-- 订单列表 -->
    <div v-else class="order-list">
      <template v-if="loading">
        <el-skeleton
            v-for="i in pagination.pageSize"
            :key="i"
            animated
            :rows="3"
        />
      </template>

      <template v-else>
        <el-empty v-if="orders.length === 0" :description="`暂无${currentTabLabel}订单`" />

        <template v-else>
          <el-card
              v-for="order in orders"
              :key="order.id"
              class="order-card"
          >
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-meta">
                <span class="order-no">订单号：{{ order.orderNo }}</span>
                <span class="create-time">
                {{ formatDateTime(order.createTime) }}
              </span>
              </div>
              <el-tag
                  :type="statusMap[order.orderStatus].type"
                  effect="dark"
                  class="status-tag"
              >
                {{ statusMap[order.orderStatus].text }}
              </el-tag>
            </div>

            <!-- 订单内容 -->
            <div class="order-content">
              <!-- 基本信息 -->
              <el-descriptions :column="2" border>
                <el-descriptions-item label="房间名称">
                  {{ order.roomName }}
                </el-descriptions-item>
                <el-descriptions-item label="店家名称">
                  {{ order.shopName }}
                </el-descriptions-item>
                <el-descriptions-item label="预约时间">
                  {{ formatDate(order.appointmentDate) }}
                  {{ order.startTime }} - {{ order.endTime }}
                </el-descriptions-item>
                <el-descriptions-item label="订单金额">
                  <span class="price">¥{{ order.price.toFixed(2) }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="支付时间" v-if="order.payTime">
                  {{ formatDateTime(order.payTime) }}
                </el-descriptions-item>
              </el-descriptions>

              <!-- 陪玩信息 -->
              <div class="escort-section">
                <h4>陪玩</h4>
                <div class="escort-list">
                  <div
                      v-for="(img, index) in order.escortImgList"
                      :key="index"
                      class="escort-item"
                  >
                    <el-avatar :src="img" />
                    <span class="escort-name">
                    {{ order.escortNameList?.[index] || '未知陪玩' }}
                  </span>
                  </div>
                  <span v-if="!order.escortImgList?.length" class="no-escort">未选择陪玩</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <el-button
                    v-if="order.orderStatus === '30'"
                    type="primary"
                    @click="showPaymentDialog(order)"
                >
                  立即支付
                </el-button>
                <el-button
                    v-if="order.orderStatus === '60'"
                    type="success"
                    @click="showEvaluationDialog(order)"
                >
                  发表评价
                </el-button>
                <el-popconfirm
                    v-if="order.orderStatus === '90'"
                    title="确定要删除该订单吗？"
                    @confirm="handleDelete(order.id)"
                >
                  <template #reference>
                    <el-button type="danger">删除订单</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </el-card>

          <!-- 分页 -->
          <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :background="true"
              layout="prev, pager, next"
              @current-change="fetchOrders"
          />
        </template>
      </template>
    </div>

    <!-- 支付对话框 -->
    <el-dialog v-model="showPayment" title="选择支付方式" width="500px">
      <div class="payment-methods">
        <div class="balance-info" v-if="userAccount">
          当前余额：¥{{ userAccount.accountBalance?.toFixed(2) }}
        </div>
        <el-radio-group v-model="paymentMethod">
          <el-radio label="balance" border>
            <div class="method-item">
              <el-icon><Wallet /></el-icon>
              <span>余额支付</span>
            </div>
          </el-radio>
          <el-radio label="alipay" border>
            <div class="method-item">
              <el-icon><Odometer /></el-icon>
              <span>支付宝支付</span>
            </div>
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <el-button @click="showPayment = false">取消</el-button>
        <el-button
            type="primary"
            @click="handlePayment"
            :loading="payLoading"
        >
          确认支付
        </el-button>
      </template>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog v-model="showEvaluation" title="订单评价" width="800px">
      <div class="evaluation-form">
        <div class="order-eval">
          <h3>订单整体评价</h3>
          <el-rate v-model="orderEvaluation.rating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
          <el-input
              v-model="orderEvaluation.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入对本次订单的整体评价"
          />
        </div>

        <div class="escort-evals">
          <h3>陪玩评价</h3>
          <div
              v-for="(escort, index) in currentOrder?.escortImgList || []"
              :key="index"
              class="escort-eval-item"
          >
            <div class="escort-info">
              <el-avatar :src="escort" />
              <span>{{ currentOrder.escortNameList?.[index] || '未知陪玩' }}</span>
            </div>
            <div class="eval-content">
              <el-rate v-model="escortEvaluations[index].rating" />
              <el-input
                  v-model="escortEvaluations[index].comment"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入对该陪玩的评价"
              />
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showEvaluation = false">取消</el-button>
        <el-button
            type="primary"
            @click="submitEvaluation"
            :loading="evalLoading"
        >
          提交评价
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, watch, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import {
  Wallet, Odometer, User,
  CircleCheck, Clock, Money,
  Ticket, Box, ChatLineSquare,
  Finished
} from '@element-plus/icons-vue'
import axios from "axios";

// 状态配置
const orderTabs = [
  { status: '30', label: '待付款', icon: Money },
  { status: '50', label: '待参加', icon: Ticket },
  { status: '60', label: '待评价', icon: ChatLineSquare },
  { status: '70', label: '已完成', icon: Finished }
]

const statusMap = {
  '30': { text: '待付款', type: 'danger' },
  '50': { text: '待参加', type: 'warning' },
  '60': { text: '待评价', type: 'primary' },
  '70': { text: '已完成', type: 'success' }
}

// 数据相关
const activeStatus = ref('30')
const orders = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  pageSize: 8,
  total: 0
})

// 支付相关
const showPayment = ref(false)
const paymentMethod = ref('balance')
const payLoading = ref(false)
const currentOrder = ref(null)
const userAccount = ref(null)

const currentUser = ref(getUser())

// 评价相关
const showEvaluation = ref(false)
const evalLoading = ref(false)
const orderEvaluation = reactive({
  rating: 5,
  comment: ''
})
const escortEvaluations = ref([])

// 计算属性
const currentTabLabel = computed(() => {
  return orderTabs.find(t => t.status === activeStatus.value)?.label || ''
})

// 日期格式化方法
const formatDate = (dateStr) => {
  return dayjs(dateStr).format('YYYY-MM-DD dddd')
}

const formatDateTime = (dateStr) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm')
}

// 获取订单数据
const fetchOrders = async () => {
  try {
    loading.value = true
    const params = {
      orderStatus: activeStatus.value,
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      userId: currentUser.value.id // 从用户信息获取
    }

    const res = await axios.get(BASE_URL+'/v1/schedule/order/select', { params })
    if (res.data.code === 2000) {
      orders.value = res.data?.data?.map(order => ({
        ...order,
        escortImgList: order.escortImgList || [],
        escortNameList: order.escortNameList || []
      })) || []
      pagination.value.total = res.data.data?.total || 0
    }
  } catch (error) {
    ElMessage.error('获取订单失败')
  } finally {
    loading.value = false
  }
}

// 处理状态变化
const handleStatusChange = () => {
  pagination.value.page = 1 // 切换状态时重置到第一页
  fetchOrders()
}

// 支付对话框
const showPaymentDialog = async (order) => {
  currentOrder.value = order
  showPayment.value = true
  try {
    const res = await axios.get(BASE_URL+`/v1/user-account/select/${currentUser.value.id}`)
    if (res.data.code === 2000) {
      userAccount.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取账户信息失败')
  }
}

// 处理支付
const handlePayment = async () => {
  try {
    payLoading.value = true
    if (paymentMethod.value === 'balance') {
      await axios.post(BASE_URL+`/v1/schedule/order/pay/${currentOrder.value.id}`)
      ElMessage.success('支付成功')
    } else {
      window.open(BASE_URL+`/v1/schedule/order/alipay/${currentOrder.value.id}`, '_blank')
    }
    await fetchOrders()
    showPayment.value = false
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '支付失败')
  } finally {
    payLoading.value = false
  }
}

// 评价对话框
const showEvaluationDialog = (order) => {
  currentOrder.value = order
  showEvaluation.value = true
  orderEvaluation.rating = 5
  orderEvaluation.comment = ''
  escortEvaluations.value = (order.escortImgList || []).map((_, index) => ({
    escortId: order.escortIdList?.[index],
    rating: 5,
    comment: ''
  }))
}

// 提交评价
const submitEvaluation = async () => {
  try {
    evalLoading.value = true

    // 提交订单评价
    let response= await axios.post(BASE_URL+'/v1/evaluation/order/save', {
      orderId: currentOrder.value.id,
      rating: orderEvaluation.rating,
      comment: orderEvaluation.comment
    })

    // 修改这里：将 eval 改为 escortEval
    await Promise.all(escortEvaluations.value.map(escortEval =>
        axios.post(BASE_URL+'/v1/evaluation/escort/save', {
          ...escortEval,
          orderId: currentOrder.value.id
        })
    ))
    if(response.data.code === 4003){
      ElMessage.error(response.data.data)
    }else{
      ElMessage.success('评价提交成功')
    }
    showEvaluation.value = false
    await fetchOrders()
  } catch (error) {
    ElMessage.error('评价提交失败')
  } finally {
    evalLoading.value = false
  }
}

// 删除订单
const handleDelete = async (orderId) => {
  try {
    await axios.post(BASE_URL+`/v1/schedule/order/delete/${orderId}`)
    ElMessage.success('删除成功')
    await fetchOrders()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 分页处理
const handlePageChange = (page) => {
  pagination.value.page = page
  fetchOrders()
}

// 初始化加载
onMounted(fetchOrders)

// 监听分页变化
watch(
    () => pagination.value.page,
    () => fetchOrders()
)
// 监听状态变化
watch(activeStatus, () => {
  pagination.value.page = 1
  fetchOrders()
})
</script>

<style scoped>
/* 保持之前的样式不变 */
.order-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.status-nav {
  margin-bottom: 30px;
  padding: 15px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}

.status-tabs {
  display: flex;
  gap: 10px;

  :deep(.el-radio-button) {
    flex: 1;
    .el-radio-button__inner {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      width: 100%;
      padding: 15px;
      border-radius: 8px !important;
      transition: all 0.3s;
    }
  }
}

.empty-box {
  padding: 40px 0;

  .empty-image {
    width: 300px;
    opacity: 0.8;
  }
}

.order-list {
  display: grid;
  gap: 20px;
}

.order-card {
  margin-bottom: 20px;
  border-radius: 12px;
  transition: all 0.3s;
  border-left: 4px solid;

  &.status-30 { border-color: #f56c6c; }
  &.status-50 { border-color: #e6a23c; }
  &.status-60 { border-color: #909399; }
  &.status-70 { border-color: #409eff; }
  &.status-90 { border-color: #67c23a; }

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-light);

  .order-meta {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .order-no {
      font-size: 14px;
      color: var(--el-text-color-regular);
    }

    .create-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }

  .status-tag {
    font-weight: 500;
    letter-spacing: 1px;
  }
}

.escort-section {
  padding: 16px;

  h4 {
    margin: 0 0 12px;
    color: var(--el-text-color-secondary);
  }

  .escort-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }

  .escort-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    padding: 8px;
    background: var(--el-fill-color-light);
    border-radius: 8px;
  }

  .no-escort {
    color: var(--el-text-color-placeholder);
  }
}

.action-buttons {
  margin-top: 16px;
  text-align: right;
}

.payment-methods {
  padding: 20px;

  .balance-info {
    margin-bottom: 20px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 4px;
    text-align: center;
    font-size: 16px;
    color: #666;
  }

  .method-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 15px;
    width: 100%;
  }
}

.evaluation-form {
  padding: 0 20px;

  h3 {
    margin: 15px 0;
    color: #666;
  }

  .escort-eval-item {
    display: flex;
    gap: 20px;
    margin: 20px 0;
    padding: 15px;
    border: 1px solid #eee;
    border-radius: 8px;

    .escort-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      width: 120px;
    }

    .eval-content {
      flex: 1;
    }
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.list-move {
  transition: all 0.6s ease;
}
</style>